package ca.etsmtl.log730.lab3.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JFrame;

import ca.etsmtl.log730.lab3.eventbus.EventBusThread;
import ca.etsmtl.log730.lab3.events.IEvent;
import ca.etsmtl.log730.lab3.events.bank.HelloEvent;
import ca.etsmtl.log730.lab3.model.CentralBank;
import ca.etsmtl.log730.lab3.view.centralbank.Banque;


public class CentralBankController {
	private EventBusThread busTread;
	private JFrame frame;
	
	public CentralBankController() {
		this(12045);
	}
	public CentralBankController(int port) {
		setPort(port);
	}

	private int port;
	
	private CentralBank centralBank = new CentralBank();

	public CentralBank getCentralBank() {
		return centralBank;
	}

	public void setCentralBank(CentralBank centralBank) {
		this.centralBank = centralBank;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public EventBusThread getBusTread() {
		return busTread;
	}
	public void setBusTread(EventBusThread busTread) {
		this.busTread = busTread;
	}
	private boolean isWorking = false;
	public boolean isWorking() {
		return isWorking;
	}
	public void startServer() {
		EventBusThread ebt = new EventBusThread(getPort());
		System.out.println("MAIN CB CONTROLLER START!");
		isWorking = true;
		ebt.setObserver(this);
		setBusTread(ebt);
	}
	
	public void stopServer() {
		isWorking = false;
		/*
		 * won't work
		 */
		getBusTread().stop();
	}
	private List<IEvent> processedList = new ArrayList<IEvent>();
	public void processed(IEvent ie) {
		if(ie instanceof HelloEvent) {
			HelloEvent he = (HelloEvent) ie;
			centralBank.getBranches().add(((HelloEvent)ie).getBranch());
			((Banque)this.frame).getBranchTableModel().getBranches().add(he.getBranch());
			((Banque)this.frame).getBranchTableModel().fireTableDataChanged();
			
			/*
			 * On ajoute la succursale à la liste (IP + port)
			 */
			
			System.out.println(he.getBranch().getIpAddress() + ":"+ he.getBranch().getPort());
		}
		processedList.add(ie);
		((Banque)this.frame).getTextLog().setText(getEvents());
		((Banque)this.frame).getTextLog().repaint();
	}
	public List<IEvent> getProcessedList() {
		return processedList;
	}
	public void setProcessedList(List<IEvent> processedList) {
		this.processedList = processedList;
	}
	
	public String getEvents() {
		StringBuffer sb = new StringBuffer();
		for(IEvent i: processedList) {
			sb.append(i.toString() + '\n');
		}
		return sb.toString();
	}
	
	public void setEvents(String s) {
		
	}
	public JFrame getFrame() {
		return frame;
	}
	public void setFrame(JFrame frame) {
		this.frame = frame;
	}
}
